Passed
Pull Request — master (#28)
by Inumidun
01:30
created

Structure.js ➔ ???   A

Complexity

Conditions 1
Paths 2

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 1
c 3
b 0
f 0
nc 2
dl 0
loc 4
rs 10
nop 2
1
const mkdirp = require('mkdirp');
2
const path = require('path');
3
const fs = require('fs');
4
const structureSchema = require('../sample/folder-schema');
5
const baseDir = require('./baseDir');
6
7
/**
8
 * Define and build the application folder structure
9
 * @class Structure
10
 */
11
class Structure {
12
13
  /**
14
   * Creates an instance of Structure.
15
   * @param {string} extend - path to add to current working drectory
16
   * @param {any} schema - folder structure schema
17
   * @memberOf Structure
18
   */
19
  constructor(extend = '', schema) {
20
    this.schema = schema || structureSchema;
21
    this.filepath = `${baseDir.getCurrentWorkingDir()}/${extend}`;
22
  }
23
24
  /**
25
   * Move through the folder schema and create folders and files
26
   * @param {Array} dir - current directory to iterate through
27
   * @param {Array} pathname - contains each individual parent
28
   * folders name
29
   * @returns {Void} returns nothing
30
   * @memberOf Structure
31
   */
32
  traverse(dir, pathname) {
33
    if (!pathname) {
34
      pathname = [];
35
    }
36
    dir.forEach((root, index, parent) => {
37
      if (typeof root === 'object') {
38
        pathname.push(Object.keys(root)[0]);
39
        mkdirp.sync(
40
          path.join(this.filepath, `/example/${pathname.join('/')}`));
41
        this.traverse(root[Object.keys(root)[0]], pathname);
42
      } else {
43
        fs.writeFile(
44
          path.join(
45
            this.filepath,
46
            `/example/${pathname.join('/')}/${root}`),
47
          '');
48
        if (index === parent.length - 1) {
49
          pathname.pop();
50
        }
51
      }
52
    });
53
  }
54
55
  /**
56
   * Build the folder structure based off the provided schema
57
   * @returns {Promise} resolves promise when directories have been created
58
   * @memberOf Structure
59
   */
60
  build() {
61
    return new Promise((resolve) => {
62
      this.traverse(this.schema);
63
      if (baseDir.directoryExists(
64
        path.join(this.filepath, '/example/test/helper.js'))) {
65
        resolve(this.schema);
66
      }
67
    });
68
  }
69
}
70
71
module.exports = Structure;
72